<template>
  <div class="lottery">
    <div class="LotteryLayout">
      <div id="main" class="wall">
        <!-- 抽奖页面布局 -->
      </div>
      <div id="result" class="result"></div>
    </div>
    <ToolBar :running="running" :selected="selected" :btns="btns" @toggle="onToggle" @reset="onReset" @onClick="onButtonClick" />
  </div>
</template>

<script>
import ToolBar from './ToolBar.vue'
import '@/assets/js/tagcanvas.js'
import '@/assets/js/zepto.js'
import { member } from '@/utils/member.js'
export default {
  components: {
    ToolBar,
  },
  data() {
    return {
      // 初始化localStorage中的choosed数据
      choosed: JSON.parse(localStorage.getItem('choosed')) || {},
      selected: 3,// 选择的按钮
      btns: [10,5,3,2,1],// 按钮数量
      member: member,// 用户信息
      // member: [],// 用户信息
      running: false,// 是否在抽奖中
    }
  },
  
  mounted() {
    // //生成用户信息
    // this.member = []
    // for (let index = 1; index <= 100; index++) {
    //   this.member.push({"phone": index, "name": "No."+index});
    // }
    //随机打乱顺序数组
    window.shuffle=(arr)=> {
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1)); // 生成[0, i]之间的随机索引
        [arr[i], arr[j]] = [arr[j], arr[i]]; // 交换当前位置与随机位置上的元素
      }
    }
    window.shuffle(this.member)
    console.table(this.member);

    window.getKey = (item) => {
      return item.name + '-' + item.phone
    }
    
    window.speed = () => {
      return [0.1 * Math.random() + 0.01, -(0.1 * Math.random() + 0.01)]
    }

    /**
     * 抽奖函数
     * @param {number} count 获奖人数
     * @param {array} member 奖品名单
     * @param {array} choosed 已中奖名单
     */
    window.lottery = (count, member, choosed) => {
      var list = canvas.getElementsByTagName('a')
      var color = 'yellow'
      var ret = member
        .filter(function (m, index) {
          m.index = index
          return !choosed[window.getKey(m)]
        })
        .map(function (m) {
          return Object.assign(
            {score: Math.random(),}, m
          )
        })
        .sort(function (a, b) {
          return a.score - b.score
        })
        .slice(0, count)
        .map(function (m) {
          choosed[window.getKey(m)] = 1
          list[m.index].style.color = color
          return m.name + '<br/>' + m.phone
        })

      localStorage.setItem('choosed', JSON.stringify(choosed))
      
      return ret
    }


    // 实现canvas绘制、TagCanvas初始化等逻辑
    var canvas = document.createElement('canvas')
    canvas.id = 'myCanvas'
    canvas.width = document.body.offsetWidth
    canvas.height = document.body.offsetHeight
    document.getElementById('main').appendChild(canvas)
    canvas.innerHTML = this.createHTML(this.member)
    TagCanvas.Start('myCanvas', '', {
      textColour: null,
      initial: window.speed(),
      dragControl: 1,
      textHeight: 30, // 设置文本高度，即字体大小（以像素为单位）
    })
  },
  methods: {
    createHTML(member) {
      var html = ['<ul>']
      member.forEach((item, index) => {
        item.index = index
        var key = window.getKey(item)
        var color = this.choosed[key] ? 'yellow' : 'white'
        html.push(
          '<li><a href="#" style="color: ' +
            color +
            ';">' +
            item.name +
            '</a></li>'
        )
      })
      html.push('</ul>')
      return html.join('')
    },

    //ToolBar
    onButtonClick(num) {
      $('#result').css('display', 'none')
      $('#main').removeClass('mask')
      this.selected = num
    },
    onToggle() {
      if (this.running) {
        TagCanvas.SetSpeed('myCanvas', window.speed())
        var ret = window.lottery(this.selected, this.member, this.choosed)
        if (ret.length === 0) {
          $('#result').css('display', 'block').html('<span>已抽完</span>')
          return
        }
        $('#result')
          .css('display', 'block')
          .html('<span>' + ret.join('</span><span>') + '</span>')
        TagCanvas.Reload('myCanvas')
        setTimeout(function () {
          localStorage.setItem(new Date().toString(), JSON.stringify(ret))
          $('#main').addClass('mask')
        }, 300)
      } else {
        $('#result').css('display', 'none')
        $('#main').removeClass('mask')
        TagCanvas.SetSpeed('myCanvas', [5, 1])
      }
      this.running = !this.running
    },
    onReset() {
      if (confirm('确定要重置么？所有之前的抽奖历史将被清除！')) {
        localStorage.clear()
        location.reload(true)
      }
    },
  },
}
</script>

<style scoped  >
/* 在这里引入或编写CSS样式 */
.lottery {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.LotteryLayout {
  position: relative;
}
.mask {
  transition: all 1s;
  -webkit-filter: blur(5px);
  filter: blur(5px);
}

.result {
  box-sizing: border-box;
  position: absolute;
  height: 320px;
  width: 100%;
  left: 0;
  top: 50%;
  margin-top: -160px;
  text-align: center;
  padding: 1rem 23rem;
  display: none;
}

::v-deep .result span {
  display: inline-block;
  font-size: 25px;
  width: 200px;
  background: #fff;
  line-height: 30px;
  color: #000;
  margin: 5px;
  border-radius: 10px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.8);
  padding: 10px 0;
}
</style>